package edu.uoc.tds.server;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
 
import javax.swing.JOptionPane;

import edu.uoc.tds.common.UtilLenguaje;

public class GestorDisco {

    public static final String SQL_STATE_UNIQUE_VIOLATION = "23505";
    private Connection objConn;
    private UtilLenguaje txt = null;

    public GestorDisco() {
        objConn = null;
    }

  

    public void initConnection() throws Exception {
        String sUrl = null;
        String sUserName = null;
        String sPassword = null;
        Properties objProperties = new Properties();

        try {
//            FileInputStream objFIS = new FileInputStream("configuration.properties");
			InputStream objFIS = this.getClass().getClassLoader().getResourceAsStream("configuration.properties");
            objProperties.load(objFIS);
            sUrl = objProperties.getProperty("url");
            sUserName = objProperties.getProperty("username");
            sPassword = objProperties.getProperty("password");
            String driver = "org.postgresql.Driver";
            Class.forName(driver);
            objConn = DriverManager.getConnection(sUrl, sUserName, sPassword);
        } catch (FileNotFoundException eFnfe) {
            JOptionPane.showMessageDialog(null,
                    txt.getMessage("bbdd.err.fichero") + "\n" + eFnfe.getMessage(),
                    txt.getMessage("bbdd.err"), JOptionPane.ERROR_MESSAGE);
        } catch (Exception eV) { 
            eV.printStackTrace();
            JOptionPane.showMessageDialog(null,
                    txt.getMessage("bbdd.err.open") + "\n" + eV.getMessage(),
                    txt.getMessage("bbdd.err"), JOptionPane.ERROR_MESSAGE);
        }
    }

      public void closeConnection() throws Exception {
        if (objConn != null) {
            try {
                objConn.close();
            } catch (SQLException eSQL) {
                JOptionPane.showMessageDialog(null,
                        txt.getMessage("bbdd.err.close") + "\n" + eSQL.getMessage(),
                        txt.getMessage("bbdd.err"), JOptionPane.ERROR_MESSAGE);
            }
            objConn = null;
        }
    }

    public Connection getConnection() {
        return objConn;
    }
}
